import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import Router, { withRouter } from '@/router/renderRouter';
import { Card, Row, Col, Input, Select, Button, message, Spin, Modal, Popover } from 'antd';
import { useSyncCallback, deepclone } from '@/utils'
import { Storage } from '@/assets/js/storage';
import { IMG_URL } from '@/utils/constant'
import { CopyToClipboard } from 'react-copy-to-clipboard';
import Zmage from 'react-zmage';
import { 
  gradeList,
} from '@/api/api'
import { 
  getById, 
  updateInfo,
  delPayee,
  resetLoginPassword,
  resetProperty,
} from '@/api/member'
import './index.scss'; 
let orCToken = {}

const MerchantInfo = forwardRef((props, ref) => {
  const { route, history } = props
  const imgUrl = Storage.get(IMG_URL);
  const [id, setId] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalType, setModalType] = useState('');
  const [password, setPassword] = useState('');
  const [info, setInfo] = useState(null);
  const [loading, setLoading] = useState(false)
  const [gradeListOptions, setGradeListOptions] = useState([]);
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    handleFinish()
  })
  const getGradeList = async () => {
    try {
      let res = await gradeList()
      if(res.code === 0) {
        let arr = []
        res.data.forEach(item=>{
          arr.push({
            value: item.id,
            label: item.name,
          })
        })
        setGradeListOptions(arr)
      }
    } catch (error) {
      console.log(error)
    }
  }
  const changeValue = (name,val) =>{
    let obj = deepclone(info)
    obj[name] = val;
    setInfo(obj)
  }
  const delFn = async (data) => {
    let res = await delPayee({
      userId:data.userId,
      tMemberPayeeId: data.id
    });
    if(res.code === 0) {
      message.success('解绑成功') 
      searchData()
    }
  }
  
  const reset = async (type, key) => {
    try {
      setLoading(true)
      let res;
      let params = {}
      setModalType(type)
      if(type === 'loginPwd'){
        params.userId = info.id;
        res = await resetLoginPassword(params);
      }else if(type === 'resetProperty'){
        params.userId = info.id;
        params.key = key;
        res = await resetProperty(params);
      }else if(type === 'openSecondValid'){
        params.userId = info.id;
      }
      setLoading(false)
      if(res.code === 0) {
        if(type === 'loginPwd' || (type === 'resetProperty' && key==='transPwd')){
          setPassword(res.data);
          setIsModalOpen(true);
        }else{
          message.success('重置成功')
        }
        searchData()
      }
    } catch(error) {
      console.log(error)
    }
  }
  const close = () => {
    setIsModalOpen(false)
    setPassword('')
  }
  const handleFinish = async () => {
    try {
      let params = {
        memberId: id,
      }
      if (typeof orCToken.source === 'function') {
        orCToken.source('终止请求'); //取消请求
      }
      setLoading(true)
      let res = await getById(params, orCToken)
      if(res.code === 0) {
        setInfo(res.data)
      }
      setLoading(false)
    } catch(error) {
      console.log(error)
    }
  }
  const save = async () =>{
    try {
      let params = {
        userId: info.id,
        nickName: info.nickName,
        status: info.status,
        creditGrade: info.creditGradeId,
        riskRemark: info.riskRemark,
      }
      if (typeof orCToken.source === 'function') {
        orCToken.source('终止请求'); //取消请求
      }
      setLoading(true)
      let res = await updateInfo(params, orCToken)
      if(res.code === 0) {
        message.success('修改成功')
        handleFinish()
      }
      setLoading(false)
    } catch(error) {
      console.log(error)
    }
  }
  const back = () =>{
    props.setPageType('index')
    props.setParams(null)
  }
  
  const content = (
    <div className="cardsmodel">
      {
        info&&info.paySetting&&info.paySetting.map((item) => {
          if(item.payeeType === 3){
            return <>
              <div class="card">
                <a onClick={()=>{delFn(item)}}>解绑</a>
                <div className="title">{item.payeeName}</div>
                <div className="item">卡号: {item.qrcode}</div>
                <div className="item">持卡人: {item.payeeAccount}</div>
                <div className="item">开户地: {item.payeeAddress}</div>
              </div>
            </>
          }else if(item.payeeType === 1 || item.payeeType === 2 || item.payeeType === 5){
            return <>
              <div class="card">
                <a onClick={()=>{delFn(item)}}>解绑</a>
                <div className="title">{item.payeeName}</div>
                <div className="item">
                  <Zmage width={100} src={imgUrl + item.qrcode} alt=""/>
                </div>
              </div>
            </>
          }else{
            return <>
              <div class="card">
                <a onClick={()=>{delFn(item)}}>解绑</a>
                <div className="title">{item.payeeName}</div>
                <div className="item">钱包地址: {item.payeeAddress}</div>
              </div>
            </>
          }
        })
      }
    </div>
  );
  
  useEffect(() => {
    if(props.params){
    	setId(props.params.userId)
    }
    searchData()
    getGradeList()
    return () => { 
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  useImperativeHandle(ref, () => ({
    searchData,
  }))
  return (
    <>
      <div>
        <Spin spinning={loading}>
          <Card title="会员资料">
            <Row className="row">
              <Col span={8}>会员账号：{info&&info.username || '--'}</Col>
              <Col span={8} className="flex">
                <span>会员昵称：</span>
                <Input style={{width: '150px'}} value={info&&info.nickName} onChange={(e)=>{changeValue('nickName',e.target.value)}} />
              </Col>
              <Col span={8}>注册时间：{info&&info.registerTime || '--'}</Col>
            </Row>
            <Row className="row">
              <Col span={8}>
                <span>登录密码：{info&&info.hasLoginPwd ? '已设置' : '未设置'}</span>
                {
                  info&&info.hasLoginPwd===true
                  ?
                  <a className="a" onClick={()=>{reset('loginPwd')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8}>
                <span>可用余额：{info&&info.balanceAmount}</span>
                <a className="a" onClick={()=>{props.open(info)}}>修改余额</a>
              </Col>
              <Col span={8}>
                <span>不可售余额：{info&&info.noSellAmount}</span>
              </Col>
            </Row>
            <Row className="row">
              <Col span={8}>
                <span>交易密码：{info&&info.hasTransPwd ? '已设置' : '未设置'}</span>
                {
                  info&&info.hasTransPwd===true
                  ?
                  <a className="a" onClick={()=>{reset('resetProperty','WITHDRAW_PASSWORD')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8}>
                <span>锁定余额：{info&&info.knockBalanceAmount}</span>
              </Col>
              <Col span={8} className="flex">
                <span>会员状态：</span>
                <Select 
                  style={{width: '150px'}}
                  value={info&&info.status}
                  onChange={(e)=>{changeValue('status',e)}}
                  options={[
                   {value: 1, label: '启用'},
                   {value: 2, label: '停用'},
                   {value: 3, label: '冻结资金'},
                  ]} 
                />
              </Col>
            </Row>
            <Row className="row">
              <Col span={8}>
                <span>手机号码：{info&&info.hasPhoneNum ? '已设置' : '未设置'}</span>
                {
                  info&&info.hasPhoneNum===true
                  ?
                  <a className="a" onClick={()=>{reset('phoneNum')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8}>
                <span>用户类型：{info&&info.userType===1?'正式会员':(info&&info.userType===0?'内部会员':'--')}</span>
              </Col>
              <Col span={8} className="flex">
                <span>会员等级：</span>
                <Select 
                  style={{width: '150px'}}
                  value={info&&info.creditGradeId?parseInt(info.creditGradeId):''}
                  onChange={(e)=>{changeValue('creditGradeId',e)}}
                  options={gradeListOptions} 
                />
              </Col>
            </Row>
            <Row className="row">
              <Col span={8} className="flex">
                <span>真实姓名：{info&&info.realName ? info.realName : '未设置'}</span>
                {
                  info&&info.realName
                  ?
                  <a className="a" onClick={()=>{reset('resetProperty','REAL_NAME')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8} className="flex">
                <span>收付款设置：{info&&info.paySetting&&info.paySetting.length>0 ? '' : '未设置'}</span>
                {
                  info&&info.paySetting&&info.paySetting.length>0
                  ?
                  <Popover content={content} trigger="click">
                    <a className="a">查看</a>
                  </Popover>
                  :
                  ''
                }
              </Col>
            </Row>
            <Row className="row">
              <Col span={8} className="flex">
                <span>身份证号：{info&&info.cardNum ? info.cardNum : '未设置'}</span>
                {
                  info&&info.cardNum
                  ?
                  <a className="a" onClick={()=>{reset('resetProperty','CARD_NUM')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8} className="flex">钱包地址：{info&&info.memberWallet || '--'}</Col>
            </Row>
            <Row className="row">
              <Col span={24} className="flex">
                <span>风控备注：</span>
                <Input.TextArea 
                  value={info&&info.riskRemark} 
                  onChange={(e)=>{changeValue('riskRemark',e.target.value)}}
                  rows={3} />
              </Col>
            </Row>
            <div style={{display: 'flex','justifyContent': 'space-around'}}>
              <Button onClick={()=>{back()}}>取消</Button>
              <Button type="primary" loading={loading} onClick={()=>{save()}}>确定</Button>
            </div>
          </Card>
        </Spin>
        
        <Modal title="提示" visible={isModalOpen} onOk={close} onCancel={close}
        	footer={[
        	  <Button type="primary" style={{marginLeft: '20px'}} onClick={close}>确认</Button>,
        	]}
        >
        	<p>重置{modalType === 'merchantPrivateKey'?'秘钥':'密码'}成功</p>
        	<table>
        		<tr>
        			<td>会员账号 : {info&&info.username}</td>
        			<td><CopyToClipboard
        				onCopy={()=>message.success('复制成功')}
        				text={info&&info.username}>
        				<Button type="primary" style={{marginLeft: '20px'}}>复制</Button>
        			</CopyToClipboard></td>
        		</tr>
        		<tr>
        			<td>{modalType === 'merchantPrivateKey'?'会员秘钥':'新密码'} : {password}</td>
        			<td>
        				<CopyToClipboard
        					onCopy={()=>message.success('复制成功')}
        					text={password}>
        					<Button type="primary" style={{marginLeft: '20px'}}>复制</Button>
        				</CopyToClipboard>
        			</td>
        		</tr>
        	</table>
        </Modal>
      </div>
    </>
  )
})
export default MerchantInfo